﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FraudMitigator
{
    public partial class LoginForm : Form
    {
        public User user { get; private set; }

        public LoginForm()
        {
            InitializeComponent();
        }

        public void AttemptLogin()
        {
            user = null;
            using (var context = new DataContext(Strings.GetConnectionString()))
            {
                Table<User> userTbl = context.GetTable<User>();

                user = userTbl
                    .Where(x => x.UserUsername == usernameTxtBox.Text 
                        && x.UserPassword == passwordTxtBox.Text)
                        .FirstOrDefault();
            }
        }

        private void loginBtn_Click(object sender, EventArgs e)
        {
            Login();
        }

        private void Login()
        {
            AttemptLogin();
            if (user != null)
            {
                DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                 MessageBox.Show("Invalid username or password.", "Invalid Input", MessageBoxButtons.OK);
                usernameTxtBox.Focus();
                usernameTxtBox.SelectAll();
            }
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void firstNameTxtBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) { Login(); }
        }

        private void lastNameTxtBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) { Login(); }
        }

        private void passwordTxtBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) { Login(); }
        }
    }
}
